module aescontrol(
    input clk,
    input rst_n,
    input load,
    input [4:0]CMD,     // wrpckreg  keyexp  staenc stadec
                        //    4        3        2      1  
    output en_de_sel,
    output keyexprdy,
    output encdecrdy,
    output keysel,
    output rndkren,
    output wrrndkrf,
    output [3:0]krfaddr,
    output rconen,
    output [1:0]keyadsel,
    output mixsel,
    output reginsel,
    output wrregen,
    output wrpckreg
);

    wire en_sel,de_sel;
    wire keyexp,staenc,stadec;
    wire [3:0] wrkrfaddr,rdkrfaddre,rdkrfaddrd,encstate,decstate;
    wire [1:0] keyadsele,keyadseld;
    wire mixsele,reginsele,wrregene,encrdy,mixseld,reginseld,wrregend,decrdy;
    
    assign wrpckreg = load & CMD[4];
    assign keyexp   = load & CMD[3];
    assign staenc   = load & CMD[2];
    assign stadec   = load & CMD[1];
    
    assign en_sel =  (encstate != 4'd0); // 1 en
    assign de_sel =  (decstate != 4'd0); // 1 de
    assign en_de_sel = (staenc | !encrdy) ? 1'b0 : 1'b1;

    assign krfaddr   =  en_sel ? rdkrfaddre : (de_sel?rdkrfaddrd:wrkrfaddr);
    assign keyadsel  =  en_sel ? keyadsele  : keyadseld;
    assign mixsel    =  en_sel ? mixsele    : mixseld;
    assign reginsel  =  en_sel ? reginsele  : reginseld;
    assign wrregen   =  en_sel ? wrregene   : wrregend;
    assign encdecrdy =  encrdy & decrdy;

    keyexpfsm  keyexpfsm(clk,!rst_n,keyexp,keysel,rndkren,wrrndkrf,wrkrfaddr,rconen,keyexprdy);
    encryfsm   encryfsm(clk,!rst_n,staenc,keyadsele,mixsele,reginsele,wrregene,rdkrfaddre,encrdy,encstate);
    decryfsm   decryfsm(clk,!rst_n,stadec,keyadseld,mixseld,reginseld,wrregend,rdkrfaddrd,decrdy,decstate);
    
endmodule